/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
//寻找目标值target的索引区间
function searchRange(nums, target) {
  // 寻找左边界：右边界左扩，最终left即左边界
  function findLeft() {
    let left = 0, right = nums.length - 1
    while (left <= right) {
      let mid = Math.floor((left + right) / 2)
      //当nums[mid]等于target时，但是nums[mid]不一定是首个等于target的数组元素，右边界需要继续左扩
      if (nums[mid] >= target) {
        //右边界左扩
        right = mid - 1
      } else {
        left = mid + 1
      }
    }
    //最终的left即左边界
    return left
  }
  // 寻找右边界：左边界右括，最终right即右边界
  function findRight() {
    let left = 0, right = nums.length - 1
    while (left <= right) {
      let mid = Math.floor((left + right) / 2)
      //当nums[mid]等于target时，但是nums[mid]不一定是末个等于target的数组元素，左边界需要继续右括
      if (nums[mid] <= target) {
        //左边界右括
        left = mid + 1
      } else {
        right = mid - 1
      }
    }
    // 最终的right即右边界
    return right
  }

  //调用函数寻找左右边界
  const leftIndex = findLeft()
  const rightIndex = findRight()

  //检查是否存在target
  if (leftIndex <= rightIndex && nums[leftIndex] === target && nums[rightIndex] === target) {
    return [leftIndex, rightIndex]
  }

  return [-1, -1]
}

